package encapsulator;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import doublelinkedlist.LinkedList;
import doublelinkedlist.exceptions.InvalidDataParameterException;
import doublelinkedlist.exceptions.LinkedListIndexException;
import exceptions.InvalidParameterException;

public class MethodEncapsulator {

	private LinkedList methodContainers;

	public MethodEncapsulator() {
		methodContainers = new LinkedList();
	}

	public void addMethod(Method m, Object obj)
			throws InvalidParameterException {

		MethodObjectContainer moc = new MethodObjectContainer(m, obj);
		try {
			methodContainers.add(moc);
		} catch (InvalidDataParameterException e) {
			System.out.println("No way to get here");
		}

	}

	public Method getMethod(int index) throws InvalidParameterException {

		MethodObjectContainer moc;
		try {
			moc = (MethodObjectContainer) methodContainers.get(index);
		} catch (LinkedListIndexException e) {
			throw new InvalidParameterException(
					"You've given an invalid index!", e);
		}

		return moc.getMethod();

	}

	public void executeMethod(int index) throws InvalidParameterException {

		MethodObjectContainer moc;
		try {
			moc = (MethodObjectContainer) methodContainers.get(index);
		} catch (LinkedListIndexException e) {
			throw new InvalidParameterException(
					"You've given an invalid index!", e);
		}
		Method m = moc.getMethod();
		Object obj = moc.getObject();
		try {
			m.invoke(obj);
		} catch (IllegalAccessException | IllegalArgumentException
				| InvocationTargetException e) {
			e.printStackTrace();
		}

	}

	public void remove(int index) throws InvalidParameterException {

		try {
			methodContainers.remove(index);
		} catch (LinkedListIndexException e) {
			throw new InvalidParameterException(
					"You've given an invalid index!", e);
		}

	}

}
